package cn.edu.cqut.mdm.core.module;

import java.io.Serializable;
import java.lang.reflect.Method;

public class RemoteMethod implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 8252827056777409717L;
	
	private String name;
	private transient Class<?>[] parameterTypes;
	private transient Class<?> returnType;
	private String[] parameterTypeNames;
	private String returnTypeName;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Class<?>[] getParameterTypes() {
		return parameterTypes;
	}
	public void setParameterTypes(Class<?>[] parameterTypes) {
		this.parameterTypes = parameterTypes;
		parameterTypeNames = new String[parameterTypes.length];
		for(int i = 0;i < parameterTypes.length;i++) {
			parameterTypeNames[i] = parameterTypes[i].getName();
		}
	}
	public Class<?> getReturnType() {
		return returnType;
	}
	public void setReturnType(Class<?> returnType) {
		this.returnType = returnType;
		returnTypeName = returnType.getName();
	}
	
	
	public String[] getParameterTypeNames() {
		return parameterTypeNames;
	}
	public void setParameterTypeNames(String[] parameterTypeNames) {
		this.parameterTypeNames = parameterTypeNames;
		parameterTypes = new Class<?>[parameterTypeNames.length];
		for(int i = 0;i < parameterTypes.length;i++) {
			try {
				parameterTypes[i] = Class.forName(parameterTypeNames[i]);
			} catch (ClassNotFoundException e) {
				parameterTypes[i] = getPrimitiveType(parameterTypeNames[i]);
			}
		}
	}
	public String getReturnTypeName() {
		return returnTypeName;
	}
	public void setReturnTypeName(String returnTypeName) {
		this.returnTypeName = returnTypeName;
		try {
			this.returnType = Class.forName(returnTypeName);
		} catch (ClassNotFoundException e) {
			this.returnType =  getPrimitiveType(returnTypeName);
		}
	}
	public static RemoteMethod fromMethod(Method method) {
		RemoteMethod remoteMethod = new RemoteMethod();
		remoteMethod.setName(method.getName());
		remoteMethod.setParameterTypes(method.getParameterTypes());
		remoteMethod.setReturnType(method.getReturnType());
		return remoteMethod;
	}
	private Class<?> getPrimitiveType(String name){
		if (name.equals("byte")) return byte.class;
		if (name.equals("short")) return short.class;
		if (name.equals("int")) return int.class;
		if (name.equals("long")) return long.class;
		if (name.equals("char")) return char.class;
		if (name.equals("float")) return float.class;
		if (name.equals("double")) return double.class;
		if (name.equals("boolean")) return boolean.class;
		if (name.equals("void")) return void.class;
		throw new IllegalArgumentException();
	}
}
